
import { address} from '../../../js/modules/store.js';
import { dialog, api,storage } from '../../../js/util';
import { area } from '../../../js/modules/gloab';
const app = getApp()
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      this.pickerAddress = this.selectComponent("#pickerAddress");
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    isLogin:{
      type:Boolean,
      value:false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    addrlist:[],
    region: [],
    editAdr:{},
    location_key :"location_key"
  },
  /**
   * 生命周期（布局完成后执行）
   */
  ready: function (options) {


  },
 
  /**
   * 组件的方法列表
   */
  methods: {
    getDefaultAddress(){
      let that = this;
      let obj = area.getCacheLocation();
      //优先使用缓存
      if (obj.Code.length > 0) {
        this.triggerSelectEvent(obj.Province, obj.City, obj.Area, obj.Code,obj);
        this.set_default_area("", "", "");
        return;
      }

      let { isLogin}=this.data;
      if (!isLogin){
        this.setLocatoin();
        return;
      }
      address.getDefaultAddress(function(ads){
        that.setLocatoin(ads)
      });
    },
    /**设置定位 */
    setLocatoin(addr){
      let obj ={};
      let location = app.globalData.location;
      //默认地址不为空时，使用默认地址
      if (addr!=undefined&&addr.Province!=undefined&&addr.City!=undefined&&addr.Area!=undefined){
        obj = this.pickerAddress.getCodeByAddress(addr.Province, addr.City, addr.Area);
      }
      //使用定位地址
      else if (location != undefined && location.adcode.length > 0) {
        this.decorateLocation(obj, location);
      }
      //如果没有定位，再次发起定位
      if (obj.code==undefined||obj.code.length==0){
      app.getCurrentLocation(api.amapKey,(res) => {
        this.decorateLocation(obj, res);
        //触发事件
        this.triggerSelectEvent(obj.province, obj.city, obj.area, obj.code);
        })
      }
      else{
        //触发事件
        this.triggerSelectEvent(obj.province, obj.city, obj.area, obj.code, obj);
      }
    
      //设置三级联运的默认地址
      this.set_default_area("", "", "");
    },
    decorateLocation(obj,location){
      obj.code = location.adcode;
      obj.area = location.district;
      obj.city = location.city;
      obj.province = location.province;
    },
    /**
     * 加载地址列表
     */
    loadAdressList(e){
      let that = this;
      let { location, isLogin, editAdr}=this.data;
      this.showModal(e);
      if (isLogin){
        address.loadUserAddressList('',function (content) {
          content.map((c)=>{
            if(c.Province.replace("省","")==editAdr.Province&&c.Area==editAdr.Area){
              c.IsChecked='1';
            }
            else{
              c.IsChecked = '0';
            }
          });
          that.setData({
            addrlist: content
          });       
        });
      }
    },
    set_default_area(province, city, area) {

      this.pickerAddress.set_default_area(province, city, area, (region) => {
        //this.onColumnChangeEvent({ detail: { region: region } });
      });
    },
    onColumnChangeEvent(e) {
      let { region,code } = e.detail;
      this.triggerSelectEvent(region[0], region[1], region[2], code);
    },

    /**
     * 选中现有地址
     */
    selectedAdress(e){
      let eq = e.currentTarget.dataset.idx;
      let addr = this.data.addrlist[eq];
      console.log(addr, eq, this.data.addrlist)
      let p = addr.Province // 省
      let c = addr.City // 市
      let d = addr.Area // 区
      // 移除最后的省文字
      if (/省$/.test(p)) {
        p = p.slice(0, p.length - 1)
      }
      // 移除最后的市文字
      if (/市$/.test(c)) {
        c = c.slice(0, c.length - 1)
      }
      console.log(p, c, d)
      let obj=this.pickerAddress.getCodeByAddress(p, c, d);
      if(obj.code==""){
        obj.code = this.data.location.adcode;
        obj.area = this.data.location.area;
      }
      addr.IsChecked='1';
      let key ="addrlist["+eq+"]";
      this.setData({
        [key]:addr
      })
      this.triggerSelectEvent(obj.province, obj.city, obj.area, obj.code,addr);
    },
    triggerSelectEvent(province, city, district, code, ads){
      let { editAdr, location_key } = this.data;
      editAdr.Province = province;
      editAdr.City = city;
      editAdr.Area = district;
      editAdr.Code = code;   
      if (ads && ads.Id>0){
        editAdr.AddressId = ads.Id;
        editAdr.Address=ads.Address;
        editAdr.Name= ads.Name;
        editAdr.Mobile=ads.Mobile;
      }
      area.setCacheLocation(editAdr);
      this.triggerEvent('selectedAdress', editAdr);
      this.hideModal();
    },
    /**
     * 解析地址
     */
    parseAddress(addr){
      let obj= this.pickerAddress.getCodeByAddress(addr.Province, addr.City, addr.Area);
      if (obj.code != "") {
        addr.code=obj.code;
      }
      return addr;
    },
    /**
   * 显示遮罩层
   */
    showModal: function (evt) {
      dialog.showModal(this, 'showModalStatus')
    },
    /**
     * 隐藏遮罩层
     */
    hideModal: function () {
      dialog.hideModal(this, 'showModalStatus')
    },
    preventTouchMove() {

    }
  }
})
